<?PHP

	class tpl_chat {

		public static function chat_page(){

			return	tpl_globals::header() .
				tpl_globals::outer_global_styles() .
				tpl_globals::global_styles_shared() .
				tpl_globals::form_styles() .
				<<<EOV
<style type='text/css'>

	.chat_header {
		background: url(./themes/default/images/chat_header.png);
		width: 700px;
		height: 83px;
		margin: auto;
		position: relative;
	}

	.chat_header .mbar {
		position: absolute;
		left: 153px;
		top: 6px;
		height: 40px;
		width: 500px;
	}

	.chat_header #tbar {
		position: absolute;
		top: 47px;
		left: 133px;
		height: 30px;
		width: 507px;
	}

	.chat_header .logo {
		position: absolute;
		top: 7px;
		left: 8px;
		width: 97px;
		height: 69px;
	}

	.chat_header .tbutton, .chat_header .xbutton, .chat_header .t2button,
	.chat_header .tbutton2, .chat_header .xbutton2, .chat_header .t2button2 {
		position: absolute;
		top: 46px;
		width: 27px;
		height: 32px;
		cursor: pointer;
		background: url(./themes/default/images/header_buttons.png);
	}

	.chat_header .tbutton, .chat_header .tbutton2 {
		left: 106px;
	}

	.chat_header .tbutton2 {
		background-position: 0px 32px;
	}

	.chat_header .xbutton, .chat_header .xbutton2 {
		left: 667px;
		background-position: 27px 0px;
	}

	.chat_header .xbutton2 {
		background-position: 27px 32px;
	}

	.chat_header .t2button, .chat_header .t2button2 {
		left: 640px;
		background-position: 55px 0px;
	}

	.chat_header .t2button2 {
		background-position: 55px 32px;
	}

	.menubar_button_norm, .menubar_button_hover {
		float: left;
		height: 30px;
		width: 100px;
		color: black;
		font-weight: bold;
		font-size: 16px;
		text-align: center;
		padding-top: 10px;
		cursor: pointer;
	}

	.menubar_button_hover {
		color: white;
		background: url(./themes/default/images/mainbar_over.png);
	}

	.tab_norm, .tab_hover, .tab_alert_norm, .tab_alert_hover, .tab_active {
		background: url(./themes/default/images/tabs.png);
		height: 30px;
		width: 100px;
		cursor: pointer;
		float: left;
		font-size: 10px;
		overflow: hidden;
	}

	.tab_norm div, .tab_hover div, .tab_alert_norm div, .tab_alert_hover div, .tab_active div, .tab_alert_norm div, .tab_alert_hover  div {
		height: 13px;
		margin-top: 8px;
		margin-left: 7px;
		width: 87px;
		overflow: hidden;
	}

	.tab_alert_norm {
		background-position: 0px -62px;
	}

	.tab_hover, .tab_active, .tab_alert_hover {
		background-position: 0px -31px;
		color: white;
	}

	.online_user_norm, .online_user_hover {
		font-size: 12px;
		height: 20px;
		color: #24517F;
		text-decoration: none;
		cursor: pointer;
	}

	.online_user_hover {
		color: #3981CB;
		text-decoration: underline;
	}

	#userlist_menu {
		width: 150px;
		border: 1px solid #797b7f;
		position: absolute;
		display: none;
		z-index: 2;
		/*background: url(./themes/default/images/menutest1.jpg) #E3E8EF;*/
	}

	#userlist_menu .item_norm, #userlist_menu .item_hover {
		background: url(./themes/default/images/dropdown_menu_bg.png);
		font-size: 12px;
		padding: 2px;
		padding-left: 20px;
		height: 16px;
		cursor: pointer;
		color: #24517F;
	}

	#userlist_menu .item_hover {
		background-position: 0px -21px;
		/*background: url(./themes/default/images/overlay.png);*/
		color: white;
	}

	#userlist_menu .item_header {
		text-align: center;
		font-weight: bold;
		font-size: 12px;
		background: url(./themes/default/images/dropdown_menu_bg.png) #ccd1d7;
		background-position: 0px -42px;
		height: 16px;
		padding: 2px;
	}

	.sysmessage {
		color: blue;
		font-style: italic;
		font-weight: bold;
	}

	.other {
		color: #2e9200;
		font-weight: bold;
	}

	.you {
		color: #004b92;
		font-weight: bold;
	}
</style>

<script language='javascript' type='text/javascript'>
	var yourSession = '{$GLOBALS['OUTPUT']->ses}';
	var yourData = {$GLOBALS['OUTPUT']->your_data};
	var yourId = yourData['uid'];
	var soundPlayed = false;
	var disableSounds = false;
	var scrollTabBarLevel = 0;
	var scrollTabBarInterval;
	var activeUserList = 'room_list';
	var activeTab = null;
	var tabs = new Array();
	var buddyList = new onlineList_manager();
	var openMenu = false;
	var lastOpenTime = 0;
	var PERMS = {$GLOBALS['OUTPUT']->perms};
EOV
.
				tpl_js::db_update_core() .
<<<EOV
	var csdb = new csdb();
	var updater = new x7chat_ajson();
	updater.set_callback(csdb.operation);
	var updaterInterval = setInterval("updater.send_request();",500);

	var justCreated = new Array();

	document.onmouseup = function(){
		scrollTabBarLevel = 0;
	}

	function canAccessRCP(roomId){

		require_perms = new Array();
		require_perms[0] = 'EDIT_ROOM_ACCESS';
		require_perms[1] = 'BAN_KICK_USER';
		require_perms[2] = 'EDIT_ROOM_PERMS';
		require_perms[3] = 'EDIT_ROOM_SETTINGS';
		require_perms[4] = 'MUTE_USER';
		require_perms[5] = 'SET_ROOM_LOG';

		for(key in require_perms){
			if(has_permission(require_perms[key],yourId,roomId))
				return true;
		}

		return false;
	}

	function doScrollTabBar(){
		if(scrollTabBarLevel == 0)
			clearInterval(scrollTabBarInterval);
		else{
			document.getElementById('tbar').scrollLeft += scrollTabBarLevel;
			scrollTabBarLevel += (scrollTabBarLevel > 0) ? 1 : -1;
		}
	}

	function startScrollingTabBar(dir){
		clearInterval(scrollTabBarInterval);
		scrollTabBarLevel = dir;
		scrollTabBarInterval = setInterval("doScrollTabBar();",'50');
	}

	function openUserList(list,force){
		if(list == activeUserList && !force) return;

		if(list == 'buddy_list'){
			// Open buddylist
			document.getElementById(activeUserList+'_btn').className = 'cssbox_nav_button_left_norm';
			document.getElementById(list+'_btn').className = 'cssbox_nav_button_right_hover';
			buddyList.activate();
		}else{
			// Open roomlist
			if(activeTab == null || !tabs[activeTab].allowRoomList)
				return;

			document.getElementById(activeUserList+'_btn').className = 'cssbox_nav_button_right_norm';
			document.getElementById(list+'_btn').className = 'cssbox_nav_button_left_hover';
			tabs[activeTab].onlineList.activate();
		}

		activeUserList = list;
	}

	function onlineList_manager(){
		var listHTML = document.createElement('div');
		var listUsers = new Array();

		this.activate = function(){
			if(document.getElementById('online_list_display').firstChild)
				document.getElementById('online_list_display').removeChild(document.getElementById('online_list_display').firstChild);
			document.getElementById('online_list_display').appendChild(listHTML);
		}

		this.hasUser = function(uid){
			if(listUsers[uid])
				return true;
			return false;
		}

		// ToDO: Check that this does not generate room enter messages on a status change
		this.addOnlineUser = function(uid,name,status){
			toReturn = true;

			if(!listUsers[uid]){
				listUsers[uid] = document.createElement('div');
				listUsers[uid].uid = uid;
				listUsers[uid].name = name;
				listUsers[uid].className = 'online_user_norm';
				listHTML.appendChild(listUsers[uid]);
			}else{
				toReturn = false;
			}

			status = status ? ' ('+status+')' : '';

			if(!listUsers[uid].status || listUsers[uid].status != status){
				listUsers[uid].status = status;
				listUsers[uid].innerHTML = "<div onmouseover=\"this.className='online_user_hover'\" onmouseout=\"this.className='online_user_norm'\" onclick=\"showUserMenu(event,"+uid+");\">"+name+status+"</div>";
			}

			return toReturn;
		}

		this.removeOnlineUser = function(uid){
			if(!listUsers[uid]) return false;

			listHTML.removeChild(listUsers[uid]);

			delete listUsers[uid];
			return true;
		}

		this.regenerateList = function(){
			for(key in listUsers){
				name = listUsers[key].name;
				status = listUsers[key].status;
				this.removeOnlineUser(key);
				this.addOnlineUser(key,name,status);
			}
		}

	}

	function menuBarTabDisplay(button){
		var displayController;
		var displayObject = button;

		this.init = function(controller){
			displayController = controller;
		}

		this.destroy = function(){ return false; }
		this.deactivate = function(){ displayObject.className = 'menubar_button_norm'; }
		this.activate = function(){ displayObject.className = 'menubar_button_hover'; }
		this.alert = function(){ }
	}

	function tabBarTabDisplay(label){
		var displayController;
		var displayObject;
		var displayLabel = label;

		this.init = function(controller){
			displayController = controller;

			displayObject = document.createElement('div');
			displayObject.className = 'tab_norm';
			displayObject.onmouseover=function(){ displayObject.className=displayObject.className.replace('_norm','_hover'); };
			displayObject.onmouseout=function(){ if(activeTab != displayController.tabId) displayObject.className=displayObject.className.replace('_hover','_norm'); };
			displayObject.onclick=displayController.activate;
			displayObject.innerHTML = "<div title='"+displayLabel+"'>"+displayLabel+"</div>";
			document.getElementById('tbar_tcontainer').style.width = 100 + parseInt(document.getElementById('tbar_tcontainer').style.width) +'px';
			document.getElementById('tbar_tcontainer').appendChild(displayObject);
		}

		this.destroy = function(){
			document.getElementById('tbar_tcontainer').removeChild(displayObject);
			document.getElementById('tbar_tcontainer').style.width = -100 + parseInt(document.getElementById('tbar_tcontainer').style.width) +'px';
			return true;
		}

		this.deactivate = function(){ displayObject.className = 'tab_norm'; }
		this.activate = function(){ displayObject.className = 'tab_active'; }
		this.alert = function(){ displayObject.className = 'tab_alert_norm'; }
	}

	function browser_tab(id,data,display){
		var tabId = id;
		this.tabId = tabId;
		var tabData = data;
		this.tabData = tabData;
		var tabDisplay = display;
		this.allowRoomList = false;

		var frameBuffer = document.createElement('iframe');
		frameBuffer.src = data['url'];
		frameBuffer.style.height = '420px';
		frameBuffer.style.width = '100%';
		frameBuffer.frameBorder = 0;
		frameBuffer.style.display = 'none';
		document.getElementById('browser_box').appendChild(frameBuffer);

		if(tabs[tabId]){ return; }
		tabs[tabId] = this;

		this.destroy = function(){
			if(activeTab == tabId)
				openRoomList();

			if(tabDisplay.destroy())
				delete tabs[tabId];
		}

		this.deactivate = function(){
			document.getElementById('browser').style.display = 'none';
			frameBuffer.style.display = 'none';
			tabDisplay.deactivate();
		}

		this.activate = function(){
			if(activeTab == tabId) return;
			if(activeTab != null) tabs[activeTab].deactivate();

			tabDisplay.activate();

			document.getElementById('browser').style.display = 'block';
			frameBuffer.style.display = 'block';

			activeTab = tabId;
		}

		tabDisplay.init(this);
	}

	function message_tab(id,data,display){
		var tabId = id;
		this.tabId = tabId;
		var tabData = data;
		this.tabData = tabData;
		var tabDisplay = display;

		this.allowRoomList = (tabData['type'] == 1);

		var onlineList = new onlineList_manager();
		this.onlineList = onlineList;

		// Add tab to tab thingy if it is unique
		if(tabs[tabId]){ return; }
		tabs[tabId] = this;

		if(tabData['type'] == 1) join_room(tabData['rid']);

		tabData['typingBuffer'] = '';
		tabData['messageBuffer'] = '';
		tabData['onlineUsers'] = new Array();

		this.destroy = function(){
			// If this is active tab switch to another tab
			if(activeTab == tabId)
				openRoomList();

			if(tabData['type'] == 1) leave_room(tabData['rid']);

			if(tabDisplay.destroy())
				delete tabs[tabId];
		}

		this.deactivate = function(){
			document.getElementById('chat_container').style.display = 'none';
			tabData['messageBuffer'] = document.getElementById('message_window').innerHTML;
			tabData['typingBuffer'] = document.getElementById('msg').value;
			tabDisplay.deactivate();
		}

		this.activate = function(){
			if(activeTab == tabId) return;
			if(activeTab != null) tabs[activeTab].deactivate();

			tabDisplay.activate();

			document.getElementById('chat_container').style.display = 'block';
			document.getElementById('msg').value = tabData['typingBuffer'];
			document.getElementById('msg').scrollTop = 10000;
			document.getElementById('msg').focus();
			document.getElementById('message_window').innerHTML = tabData['messageBuffer'];
			scrollMessageWindow(true);

			activeTab = tabId;

			if(tabData['type'] == 1)
				openUserList('room_list',true);
			else
				openUserList('buddy_list',true);

			if(!canAccessRCP(tabData['rid']) && !justCreated[tabData['rid']])
				document.getElementById('roomcp_button').className = 'cssbox_nav_button_inactive';
			else
				document.getElementById('roomcp_button').className = 'cssbox_nav_button_left_norm';
		}

		this.add_message = function(text){
			tabData['messageBuffer'] += text;

			if(activeTab == tabId){
				preScrollMessageWindow();
				document.getElementById('message_window').innerHTML += text;
				scrollMessageWindow(false);
			}else{
				tabDisplay.alert();
			}
		}

		tabDisplay.init(this);
	}

	var preWritePosition = null;
	function preScrollMessageWindow(){
		mWin = document.getElementById('message_window');
		preWritePosition = (mWin.scrollHeight - mWin.scrollTop - mWin.offsetHeight);
	}

	function scrollMessageWindow(force){
		if(preWritePosition == null){
			mWin = document.getElementById('message_window');
			preWritePosition = (mWin.scrollHeight - mWin.scrollTop - mWin.offsetHeight);
		}
		if(force || preWritePosition < 45){
			document.getElementById('message_window').scrollTop = mWin.scrollHeight;
		}

		preWritePosition = null;
	}

	window.onload = function(){
		document.getElementById('tbar_tcontainer').style.width = '0px';

		// Load initial data
		var INIT_DATA = {$GLOBALS['OUTPUT']->init_data};
		for(key in INIT_DATA){
			csdb.operation(INIT_DATA[key]);
		}

		// Detect when enter is pressed in the message box
		document.getElementById('msg').onkeypress = messageBoxKeyPress;

		// Load sounds if possible, otherwise disable them
		try {
			document.getElementById('msgSound').Play();
		}catch(e){
			disableSounds = true;
		}

		openRoomList();
	}

	csdb.addHook('pre',checkYourData,'add','users');
	function checkYourData(INDATA){
		if(INDATA['uid'] == yourId && INDATA['email']){
			yourData = INDATA;
		}

		// Check for status change
		oldData = csdb.get('users',INDATA['uid']);
		if(oldData && oldData['status'] != INDATA['status']){
			for(key in tabs){
				if(tabs[key].onlineList && tabs[key].onlineList.hasUser(INDATA['uid']))
					tabs[key].onlineList.addOnlineUser(INDATA['uid'],INDATA['name'],INDATA['status']);
			}
		}

		if(buddyList.hasUser(INDATA['uid']))
			buddyList.addOnlineUser(INDATA['uid'],INDATA['name'],INDATA['status']);
	}

	function ua(action,id){
		send_message("/"+action+" "+id,tabs[activeTab].tabData['rid'],tabs[activeTab].tabData['type']);
	}

	function join_room(rid){
		if(!csdb.get('active_rooms',rid)){
			newRoom = new Array();
			newRoom['rid'] = rid;
			csdb.add('active_rooms',rid,newRoom);
		}
	}

	function leave_room(rid){
		csdb.remove('active_rooms',rid);
		updater.add_outdata('part',rid,++OUTID);
	}

	function set_rpass(rid,pass){
		room = csdb.get('active_rooms',rid);
		if(room){
			room['password'] = pass;
			csdb.add('active_rooms',rid,room);
		}
	}

	function addTab(tid,type,label,password){
		tmp = new message_tab(tid+'_'+type,{'type':type,'rid':tid},new tabBarTabDisplay(label));
		tabs[tid+'_'+type].activate();
		if(password) set_rpass(tid,password);
	}

	document.onclick= function(){
		if(openMenu && lastOpenTime-(new Date().getTime()) < -5){
			document.getElementById('userlist_menu').style.display = 'none';
			openMenu = false;
		}
	}

	function openRoomList(){
		if(tabs['roomlist']){
			tabs['roomlist'].activate();
		}else{
			new browser_tab('roomlist',{'url':'./index.php?act=roomlist'+yourSession},new menuBarTabDisplay(document.getElementById('roomListBtn'))); tabs['roomlist'].activate();
		}
	}

	function openRoomCP(){
		if(canAccessRCP(tabs[activeTab].tabData['rid'])){
			if(!tabs['rcp_'+tabs[activeTab].tabData['rid']])
				new browser_tab('rcp_'+tabs[activeTab].tabData['rid'],{'url':'./index.php?act=roomsettings&rid='+tabs[activeTab].tabData['rid']+yourSession},new tabBarTabDisplay('{$GLOBALS['LANG']->lang_chat->roomcp}'));
			tabs['rcp_'+tabs[activeTab].tabData['rid']].activate();
		}
	}

	function showUserMenu(e,add,forcenotbuddy){
		isBuddyList = (activeUserList == 'buddy_list' && !forcenotbuddy);
		uid = add;

		e = e || window.event;

		var cursor = {x:0, y:0};
		if(e.pageX || e.pageY){
			cursor.x = e.pageX;
			cursor.y = e.pageY;
		}else{
			var de = document.documentElement;
			var b = document.body;
			cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
			cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
		}

		cursor.x -= 150;

		document.getElementById('userlist_menu').style.top = parseInt(cursor.y) + 'px';
		document.getElementById('userlist_menu').style.left = parseInt(cursor.x) + 'px';
		document.getElementById('userlist_menu').style.display = 'block';
		openMenu = true;
		lastOpenTime = new Date().getTime();

		yourGroup = csdb.get('groups',yourData['group']);
		if(!yourGroup) return;
		thisRoom = (tabs[activeTab].tabData['type'] == 1) ? tabs[activeTab].tabData['rid'] : 0;

		theirData = csdb.get('users',uid);
		if(!theirData) return;
		theirGroup = csdb.get('groups',theirData['group']);
		if(!theirGroup) return;
		theirId = uid;

		var menuHtml = '';

		blockText = (yourData['ignore'][uid]) ? '{$GLOBALS['LANG']->lang_chat->unblock}' : '{$GLOBALS['LANG']->lang_chat->block}';

		if(has_permission('SEND_IM_MESSAGE',yourId,thisRoom))
			menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"addTab(" + uid + ",2,'" + theirData['name'] + "');\">{$GLOBALS['LANG']->lang_chat->private_chat}</div>";

		if(has_permission('USE_BUDDY_LIST',yourId,thisRoom)){
			if(!yourData['buddies'][uid])
				menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('addbuddy'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->addbuddy}</div>";
			else
				menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('removebuddy'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->removebuddy}</div>";
		}

		menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" id=\"usermenu_ignore\" onclick=\"toggleIgnore(" + uid + ")\">" + blockText + "</div>";

		if(theirData['group'] != 3)
			menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" id=\"usermenu_ignore\" onclick=\"new browser_tab('profile'+uid,{'url':'./index.php?act=profile&uid='+uid+yourSession},new tabBarTabDisplay('{$GLOBALS['LANG']->lang_chat->profile}')); tabs['profile'+uid].activate();\">{$GLOBALS['LANG']->lang_chat->profile}</div>";

		if(!isBuddyList){

			if(has_permission('BAN_KICK_USER',yourId,thisRoom) && !(has_permission('GLOBAL_ACCESS',theirId,thisRoom)))
				menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('kick'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->kick}</div>";

			if(has_permission('VIEW_IP',yourId,thisRoom))
				menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('viewip'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->viewip}</div>";

			if(has_permission('EDIT_ROOM_ACCESS',yourId,thisRoom) && !(has_permission('GLOBAL_VOICE',theirId,thisRoom))){

				if(has_permission('SEND_REGULAR_MESSAGE',theirId,thisRoom,'is_denied')){
					// They are muted
					menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('unmute'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->unmute}</div>";
				}else{
					// They are not muted
					menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('mute'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->mute}</div>";
				}

				if(tabs[activeTab].tabData['type'] == 1){
					roomData = csdb.get('rooms',tabs[activeTab].tabData['rid']);
					if(!(has_permission('SEND_REGULAR_MESSAGE',null,thisRoom))){
						// Room is in interview mode
						if(has_permission('READ_UNVOICED_USERS',theirId,thisRoom)){
							skip_mode = 'moderator';
						}else if(has_permission('READ_REGULAR_MESSAGE',theirId,thisRoom)){
							skip_mode = 'voiced';
						}else{
							skip_mode ='devoiced';
						}

						if(skip_mode != 'moderator')
							menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('moderator'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->make_moderator}</div>";
						if(skip_mode != 'voiced')
								menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('voice'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->make_voiced}</div>";
						if(skip_mode != 'devoiced')
								menuHtml += "<div class='item_norm' onmouseout=\"this.className=this.className.replace('_hover','_norm');\" onmouseover=\"this.className=this.className.replace('_norm','_hover');\" onclick=\"ua('devoice'," + uid + ")\">{$GLOBALS['LANG']->lang_chat->make_devoiced}</div>";
					}
				}
			}

		}

		document.getElementById('userlist_menu').innerHTML = "<div class='item_header'>" + theirData['name'] + "</div>" + menuHtml;
	}

	csdb.addHook('other',redirectHandler,'redirect');
	function redirectHandler(DATAIN){
		if(DATAIN['close_room'] && tabs[DATAIN['close_room'] + "_" + 1]){
			tabs[DATAIN['close_room'] + "_" + 1].destroy();
		}
		if(DATAIN['new_window_id'] && !tabs[DATAIN['new_window_id']]){
			tmp = new browser_tab(DATAIN['new_window_id'],{'url':DATAIN['new_window_url']},new tabBarTabDisplay(DATAIN['new_window_label']));
			tmp.activate();
		}
		if(DATAIN['location']){
			document.location='./index.php?act='+DATAIN['location'];
		}
	}

	csdb.addHook('other',changeSession,'chg_session');
	function changeSession(INDATA){
		yourSession = INDATA['session'];
	}

	csdb.addHook('other',addUserOnline,'online_add');
	function addUserOnline(INDATA){
		if(tabs[INDATA['rid']+"_"+1]){
			if(tabs[INDATA['rid']+"_"+1].onlineList.addOnlineUser(INDATA['uid'],INDATA['name'],INDATA['status']))
				write_message({'uid':0,'name':'','msg':'{$GLOBALS['LANG']->lang_chat->entermsg}'.replace('_u',INDATA['name']),'time':new Date().getTime()/1000,'room':INDATA['rid'],'rtype':1});
		}else if(INDATA['rid'] == 'buddylist'){
			if(buddyList.addOnlineUser(INDATA['uid'],INDATA['name'],INDATA['status']))
				write_message({'uid':0,'name':'','msg':'{$GLOBALS['LANG']->lang_chat->buddyonline}'.replace('_u',INDATA['name']),'time':new Date().getTime()/1000,'room':tabs[activeTab].tabData['rid'],'rtype':tabs[activeTab].tabData['type']});
		}
	}

	csdb.addHook('other',removeUserOnline,'online_remove');
	function removeUserOnline(INDATA){
		if(tabs[INDATA['rid'] + "_" + 1]){
			uData = csdb.get('users',INDATA['uid']);
			if(tabs[INDATA['rid'] + "_" + 1].onlineList.removeOnlineUser(INDATA['uid']) && uData && uData['name'])
				write_message({'uid':0,'name':'','msg':'{$GLOBALS['LANG']->lang_chat->leavemsg}'.replace('_u',uData['name']),'time':new Date().getTime()/1000,'room':INDATA['rid'],'rtype':1});
		}else if(INDATA['rid'] == 'buddylist'){
			uData = csdb.get('users',INDATA['uid']);
			if(buddyList.removeOnlineUser(INDATA['uid']) && uData && uData['name'])
				write_message({'uid':0,'name':'','msg':'{$GLOBALS['LANG']->lang_chat->buddyoffline}'.replace('_u',uData['name']),'time':new Date().getTime()/1000,'room':tabs[activeTab].tabData['rid'],'rtype':tabs[activeTab].tabData['type']});
		}
	}

	function has_permission(permission,user,room,return_mode){
		var allow = 0;
		var deny = 0;
		var room_allow = 0;
		var room_deny = 0;

		pgroup = PERMS[permission][0];
		pval = PERMS[permission][1];

		userData = csdb.get('users',user);
		if(userData){

			if(userData['group']){
				groupData = csdb.get('groups',userData['group']);
				if(groupData && groupData['perms'] && groupData['perms'][pgroup]){
					allow |= groupData['perms'][pgroup]['allowed'];
					deny |= groupData['perms'][pgroup]['denied'];
				}
			}

			if(userData['perms'] && userData['perms'][pgroup]){
				allow |= userData['perms'][pgroup]['allowed'];
				deny |= userData['perms'][pgroup]['denied'];
			}
		}

		if(room){
			roomData = csdb.get('rooms',room);

			if(roomData && roomData['perms'] && roomData['perms']['default'] && roomData['perms']['default'][0][pgroup]){
				room_allow |= roomData['perms']['default'][0][pgroup]['allowed'];
				room_deny |= roomData['perms']['default'][0][pgroup]['denied'];
			}

			if(user){
				// Check user/usergroup perms
				if(roomData && roomData['perms'] && roomData['perms']['user'] && roomData['perms']['user'][user] && roomData['perms']['user'][user][pgroup]){
					room_allow |= roomData['perms']['user'][user][pgroup]['allowed'];
					room_deny |= roomData['perms']['user'][user][pgroup]['denied'];
				}

				if(userData && userData['group'] && roomData && roomData['perms'] && roomData['perms']['group'] && roomData['perms']['group'][userData['group']] && roomData['perms']['group'][userData['group']][pgroup]){
					room_allow |= roomData['perms']['group'][userData['group']][pgroup]['allowed'];
					room_deny |= roomData['perms']['group'][userData['group']][pgroup]['denied'];
				}
			}

			if(return_mode == 'is_denied')
				return (pval & (room_deny|deny));
			else
				return (pval & (allow|(room_allow &~ room_deny)) &~ deny);
		}else{
			// Check global perms
			if(return_mode == 'is_denied')
				return (pval & deny);
			else
				return (pval & allow &~ deny);
		}

	}

	window.onunload = unloadWindow;
	function unloadWindow(){
		rids = csdb.getAll('active_rooms');
		for(rid in rids){
			updater.add_outdata('part',rid,++OUTID);
		}
		updater.send_request();
		//alert('{$GLOBALS['LANG']->lang_chat->exit_msg}');
	}

	function toggleIgnore(uid){
		if(yourData['ignore'][uid]){
			send_message("/unignore "+uid,tabs[activeTab].tabData['rid'],tabs[activeTab].tabData['type']);
			delete yourData['ignore'][uid];
		}else{
			send_message("/ignore "+uid,tabs[activeTab].tabData['rid'],tabs[activeTab].tabData['type']);
			yourData['ignore'][uid] = true;
		}
	}

	function send_message(message,pmto,type){
		if(message == '') return null;

		updater.add_outdata('pm2',pmto,++OUTID);
		updater.add_outdata('sendtype',type,OUTID);
		updater.add_outdata('message',message,OUTID);

		return 'ok';
	}

	function gen_timestamp(time){
		timestamp = new Date();
		timestamp.setTime(time*1000);
		G = timestamp.getHours();
		i = ''+timestamp.getMinutes();
		if(i.length == 1) i = '0'+i;
		s = ''+timestamp.getSeconds();
		if(s.length == 1) s = '0'+s;
		if(G >= 12){
			a = 'pm';
			A = 'PM';
			g = G-12;
		}else{
			a = 'am';
			A = 'AM';
			g = G;
		}
		return g + ':' + i + ':' + s;
	}

	var shown_errors = new Array();
	var error_being_shown = false;
	csdb.addHook('other',error_message,'error_message');
	function error_message(INDATA){
		if(!error_being_shown && (!shown_errors[INDATA['error_hash']] || (new Date()).getTime()-shown_errors[INDATA['error_hash']] > 60000)){
			error_being_shown = true;
			document.getElementById('message_window').innerHTML += "<div class='error_box' style='border: 1px solid red;margin: 5px;padding: 5px;'>"+INDATA['msg']+"</div>";
			error_being_shown = false;
			shown_errors[INDATA['error_hash']] = (new Date()).getTime();
		}
	}

	csdb.addHook('other',write_message,'new_message');
	function write_message(INDATA){
		if(yourData['ignore'][INDATA['uid']]) return;

		INDATA['time'] = (yourData['settings']['show_timestamps']) ? '[' + gen_timestamp(INDATA['time']) + '] ' : '';

		INDATA['msg'] = INDATA['msg'].replace(/</g,'&lt;');
		INDATA['msg'] = INDATA['msg'].replace(/>/g,'&gt;');
		INDATA['msg'] = INDATA['msg'].replace(/([^\/])www\./gi,'&dollar;1http://www.');
		INDATA['msg'] = INDATA['msg'].replace(/\[url=(.+?)\](.+?)\[\/url\]/gi,"<a href='&dollar;1' target='_blank'>&dollar;2</a>");
		INDATA['msg'] = INDATA['msg'].replace(/(http:\/\/|https:\/\/)([^ \[<]+)(?![^<>]*(>|<\/a>))/gi,"<a href=\"&dollar;1&dollar;2\" target=\"_blank\">&dollar;1&dollar;2</a>");
		INDATA['msg'] = INDATA['msg'].replace(/&lt;br \/&gt;/g,"<br />");
		INDATA['msg'] = INDATA['msg'].replace(/\\n/g,"<br />");

		INDATA['msg'] = INDATA['msg'].replace(/([A-z0-9_\-\.]+)@([A-z0-9\-\.]+)(?![^<>]*(>|<\/a>))/gi,"<a href=\"mailto: &dollar;1@&dollar;2\">&dollar;1@&dollar;2</a>");

		var regxp = new RegExp("'","gi");
		INDATA['msg'] = INDATA['msg'].replace(regxp,"&#039;");
		var filters = csdb.getAll('filteredWords');
		for(key in filters){
			if(filters[key]['replacement']){
				if(filters[key]['replacement'].substr(0,1) != '<' || yourData['settings']['show_smilies']){
					var regxp = new RegExp(key,"gi");
					INDATA['msg'] = INDATA['msg'].replace(regxp,filters[key]['replacement']);
				}
			}
		}

		if(!soundPlayed && !disableSounds && yourData['settings']['play_sounds']){
			document.getElementById('msgSound').Play();
			soundPlayed = true;
		}

		tabId = INDATA['room']+"_"+INDATA['rtype'];

		if(INDATA['name'] == ''){
			xout = "<div class='message'>" + INDATA['time'] + " <span class='sysmessage'>" + INDATA['msg'] + "</span></div>";
		}else{
			if(!yourData['settings']['show_styles'] || !INDATA['styles']['font'])
				INDATA['styles']['font'] = (yourData['settings']['styles']['font'] != '') ? yourData['settings']['styles']['font'] : '{$GLOBALS['OUTPUT']->settings['default_style']['font']}';
			if(!yourData['settings']['show_styles'] || !INDATA['styles']['color'])
				INDATA['styles']['color'] = (yourData['settings']['styles']['color'] != '') ? yourData['settings']['styles']['color'] : '{$GLOBALS['OUTPUT']->settings['default_style']['color']}';
			if(!yourData['settings']['show_styles'] || !INDATA['styles']['size'])
				INDATA['styles']['size'] = (yourData['settings']['styles']['size'] != '') ? yourData['settings']['styles']['size'] : '{$GLOBALS['OUTPUT']->settings['default_style']['size']}';

			classCss = (INDATA['uid'] != yourData['uid']) ? 'other' : 'you';
			xout = "<div class='message'>" + INDATA['time'] + "<span class='" + classCss + "' onclick='showUserMenu(event,"+INDATA['uid']+",true)'>" + INDATA['name'] + "</span>: <span style='font-family:" + INDATA['styles']['font'] + ";font-size:" + INDATA['styles']['size'] + ";color:" + INDATA['styles']['color'] + ";'>" + INDATA['msg'] + "</span></div>";

			if(!tabs[tabId] && INDATA['rtype'] == 2)
				addTab(INDATA['uid'],2,INDATA['name']);
		}

		if(tabs[tabId])
			tabs[tabId].add_message(xout);
	}

	function clearMessages(){
		tabs[activeTab].tabData['messageBuffer'] = "";
		document.getElementById('message_window').innerHTML = "";
	}

	function msgboxSubmit(){
		if(document.getElementById('msg').value == '') return;

		send_message(document.getElementById('msg').value,tabs[activeTab].tabData['rid'],tabs[activeTab].tabData['type']);

		toWrite = new Array();
		toWrite['uid'] = yourData['uid'];
		toWrite['name'] = yourData['name'];
		toWrite['msg'] = document.getElementById('msg').value;
		toWrite['time'] = new Date().getTime()/1000;
		toWrite['room'] = tabs[activeTab].tabData['rid'];
		toWrite['rtype'] = tabs[activeTab].tabData['type'];
		toWrite['styles'] = new Array();
		toWrite['styles']['font'] = '';
		toWrite['styles']['size'] = '';
		toWrite['styles']['color'] = '';

		write_message(toWrite);

		document.getElementById('msg').value = '';
		document.getElementById('msg').focus();
	}

	function messageBoxKeyPress(e){
		if(e){
			kcode = e.which;
			shift = e.shiftKey;
		}else{
			kcode = window.event.keyCode;
			shift = window.event.shiftKey;
		}

		if(kcode == 13 && shift != 1){
			msgboxSubmit();
			return false;
		}else
			return true;
	}

</script>

<div id='userlist_menu'></div>

<div class='chat_header'>
	<div class='logo'><img src='./themes/default/images/logo.png' /></div>
	<div class='mbar'>
		<div id='roomListBtn' onclick="openRoomList();" class='menubar_button_norm' onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="if(activeTab != 'roomlist') this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->roomlist}</div>
		<div onclick="if(tabs['settings']) tabs['settings'].activate(); else{ new browser_tab('settings',{'url':'./index.php?act=usersettings{$GLOBALS['OUTPUT']->ses}'},new menuBarTabDisplay(this)); tabs['settings'].activate(); }" class='menubar_button_norm' onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="if(activeTab != 'settings') this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->settings}</div>
		<div onclick="if(tabs['calendar']) tabs['calendar'].activate(); else{ new browser_tab('calendar',{'url':'./index.php?act=calendar{$GLOBALS['OUTPUT']->ses}&format=inner'},new menuBarTabDisplay(this)); tabs['calendar'].activate(); }" class='menubar_button_norm' onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="if(activeTab != 'calendar') this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->calendar}</div>
		<div onclick="if(tabs['help']) tabs['help'].activate(); else{ new browser_tab('help',{'url':'{$GLOBALS['OUTPUT']->settings['help_url']}&skin=mini'},new menuBarTabDisplay(this)); tabs['help'].activate(); }" class='menubar_button_norm' onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="if(activeTab != 'help') this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->help}</div>
		<div onclick="document.location='./index.php?logout=1'" class='menubar_button_norm' onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->logout}</div>
	</div>
	<div class='tbutton' onmousedown="startScrollingTabBar(-10);" onmouseover="this.className='tbutton2'" onmouseout="this.className='tbutton'"></div>
	<div id='tbar'>
		<div id='tbar_tcontainer'></div>
	</div>
	<div class='t2button' onmousedown="startScrollingTabBar(10);" onmouseover="this.className='t2button2'" onmouseout="this.className='t2button'"></div>
	<div class='xbutton' onmousedown="if(activeTab) tabs[activeTab].destroy();" onmouseover="this.className='xbutton2'" onmouseout="this.className='xbutton'"></div>
</div>

<div id='chat_container' style='width: 700px;margin: auto; display: none;'>

<!-- 	<div class='cssbox' style='width: 486px !important; float: left;'> -->
	<div class='cssbox' style='width: 486px !important; float: left;'>
		<div style='position: absolute; top: 6px;left: 7px;width: 472px;'>
			<div onclick="tabs[activeTab].destroy();" style='float: right;width: 94px;' class='cssbox_nav_button_right_norm' onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->exit}</div>
			<div onclick="clearMessages();" style='float: right;width: 94px;' class='cssbox_nav_button_norm' onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->clear}</div>
			<div id='roomcp_button' style='width: 94px;' class='cssbox_nav_button_left_norm' onclick="openRoomCP();" onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="this.className=this.className.replace('_hover','_norm');">{$GLOBALS['LANG']->lang_chat->roomcp}</div>
			<div style='width: 94px;' class='cssbox_nav_button_inactive'><!-- webcam --></div>
			<div style='width: 94px;' class='cssbox_nav_button_inactive'><!-- invisible --></div>
		</div>
		<div class='boxhead'><h2><div style='height: 50px;'></div></h2></div>
		<div class="boxbody" style='width: 452px;'>
			<div style='height: 300px; overflow: auto;' id='message_window'></div>
		</div>
	</div>

	<div class='cssbox' style='width: 214px !important; float: left;'>
		<div style='position: absolute;top: 6px;left: 7px;'>
			<div id='room_list_btn' style='width: 100px;' class='cssbox_nav_button_left_hover' onclick="openUserList('room_list');" onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="if(activeUserList != 'room_list'){ this.className=this.className.replace('_hover','_norm'); }">{$GLOBALS['LANG']->lang_chat->roomlist}</div>
			<div id='buddy_list_btn' style='width: 100px;' class='cssbox_nav_button_right_norm' onclick="openUserList('buddy_list');" onmouseover="this.className=this.className.replace('_norm','_hover');" onmouseout="if(activeUserList != 'buddy_list'){ this.className=this.className.replace('_hover','_norm'); }">{$GLOBALS['LANG']->lang_chat->buddylist}</div>
		</div>
		<div class='boxhead' style='width: 107px;'><h2><div style='height: 50px;'></div></h2></div>
		<div class='boxbody' style='width: 107px'>
			<div style='height: 300px; position: absolute; top: 40px; left: 15px; width: 180px; overflow: auto;' id='online_list_display'></div>
			<div style='height: 300px;'></div>
		</div>
	</div>

	<div class='cssbox simplebox' style='width: 700px !important; clear: both;'>
		<div class='boxhead'><h2><div style='height: 49px;'></div></h2></div>
		<div class='boxbody'><div style='height: 49px;'></div></div>
		<div style='position: absolute; top: 15px; left: 15px; width: 670px; height: 70px;'>
			<input type='button' style='float: right;margin-top: 20px;' value='{$GLOBALS['LANG']->lang_chat->send}' class='form_button_norm' onmouseout="this.className='form_button_norm'" onmouseover="this.className='form_button_over'" onclick="msgboxSubmit();">
			<textarea id='msg' style='height: 65px; width: 570px;'></textarea>
		</div>
	</div>

</div>

<div id='browser' class='cssbox simplebox' style='width: 700px !important; clear: both; display: none;'>
	<div class='boxhead' style='width: 350px;'><h2><div style='height: 230px;'></div></h2></div>
	<div class='boxbody' style='width: 350px;'><div style='height: 222px;'></div></div>
	<div style='position: absolute; top: 15px; left: 15px; width: 670px; height: 600px;' id='browser_box'></div>
</div>

<div id='soundControllerDisplay' style='position: absolute; top: 0px;left: 0px;width: 1px; height: 1px; overflow: hidden;'>
	<embed height='1' width='1' id='msgSound' src="./sounds/msg.swf" loop="false" quality="high" bgcolor="#ffffff" width="10" height="10" name="msgSound" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
	<embed height='1' width='1' id='enterSound' src="./sounds/enter.swf" loop="false" quality="high" bgcolor="#ffffff" width="10" height="10" name="enterSound" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</div>
EOV
.
				tpl_globals::welcome_footer() .
				tpl_globals::footer();
		}

	}
?>